const videoElement = document.querySelector('.input_video');
const canvasElement = document.querySelector('.output_canvas');
const canvasCtx = canvasElement.getContext('2d');
const clearButton = document.querySelector('#clear-btn');
const countdownDisplay = document.querySelector('#countdown-display');

canvasElement.width = 640;
canvasElement.height = 480;

let isDrawing = false;
let lastX = 0;
let lastY = 0;
let countdownInterval = null;
let countdownValue = 3;
let isCountdownActive = false;

function draw(x, y) {
    canvasCtx.strokeStyle = 'cyan';
    canvasCtx.lineWidth = 5;
    canvasCtx.lineCap = 'round';
    canvasCtx.lineJoin = 'round';
    canvasCtx.beginPath();
    canvasCtx.moveTo(lastX, lastY);
    canvasCtx.lineTo(x, y);
    canvasCtx.stroke();
    [lastX, lastY] = [x, y];
}

function clearCanvas() {
    canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
    console.log("\u753b\u5e03\u5df2\u6e05\u9664");
}

function startCountdown() {
    if (isCountdownActive) return;
    isCountdownActive = true;
    countdownValue = 3;
    countdownDisplay.textContent = countdownValue;
    countdownDisplay.style.visibility = 'visible';
    countdownInterval = setInterval(() => {
        countdownValue--;
        countdownDisplay.textContent = countdownValue;
        if (countdownValue <= 0) {
            clearCanvas();
            stopCountdown();
        }
    }, 1000);
}

function stopCountdown() {
    if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
    }
    isCountdownActive = false;
    countdownDisplay.style.visibility = 'hidden';
}

clearButton.addEventListener('click', () => {
    stopCountdown();
    clearCanvas();
});

function onResults(results) {
    if (!results.multiHandLandmarks || results.multiHandLandmarks.length === 0) {
        if (isCountdownActive) stopCountdown();
        isDrawing = false;
        return;
    }

    const landmarks = results.multiHandLandmarks[0];

    if (isCountdownActive) {
        return;
    }

    const wrist = landmarks[0];
    const indexFingerTip = landmarks[8];
    const middleFingerTip = landmarks[12];
    const ringFingerTip = landmarks[16];
    const pinkyTip = landmarks[20];

    const openHandThreshold = 0.20;
    const isHandOpen = (
        Math.hypot(indexFingerTip.x - wrist.x, indexFingerTip.y - wrist.y) > openHandThreshold &&
        Math.hypot(middleFingerTip.x - wrist.x, middleFingerTip.y - wrist.y) > openHandThreshold &&
        Math.hypot(ringFingerTip.x - wrist.x, ringFingerTip.y - wrist.y) > openHandThreshold &&
        Math.hypot(pinkyTip.x - wrist.x, pinkyTip.y - wrist.y) > openHandThreshold
    );

    const fingerExtendedThreshold = 0.20;
    const fingerCurledThreshold = 0.17;
    const isPointing = (
        Math.hypot(indexFingerTip.x - wrist.x, indexFingerTip.y - wrist.y) > fingerExtendedThreshold &&
        Math.hypot(middleFingerTip.x - wrist.x, middleFingerTip.y - wrist.y) < fingerCurledThreshold &&
        Math.hypot(ringFingerTip.x - wrist.x, ringFingerTip.y - wrist.y) < fingerCurledThreshold &&
        Math.hypot(pinkyTip.x - wrist.x, pinkyTip.y - wrist.y) < fingerCurledThreshold
    );

    if (isHandOpen) {
        startCountdown();
        isDrawing = false;
    } else if (isPointing) {
        const x = indexFingerTip.x * canvasElement.width;
        const y = indexFingerTip.y * canvasElement.height;

        if (!isDrawing) {
            isDrawing = true;
            lastX = x;
            lastY = y;
        }
        draw(x, y);
    } else {
        isDrawing = false;
    }
}

const hands = new Hands({locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`});
hands.setOptions({
    maxNumHands: 1,
    modelComplexity: 1,
    minDetectionConfidence: 0.5,
    minTrackingConfidence: 0.5
});
hands.onResults(onResults);

const camera = new Camera(videoElement, {
    onFrame: async () => {
        await hands.send({image: videoElement});
    },
    width: 640,
    height: 480
});
camera.start();

console.log("\u5e94\u7528\u5df2\u66f4\u65b0\uff0c\u79fb\u9664\u6ce8\u91ca\u540e\u529f\u80fd\u6b63\u5e38\u3002");
